# @Time :  
# @Author : Fioman 
# @Phone : 13149920693
"""
mysql数据库操作相关的logger,所有的mysql相关的logger记录都在这个文件中
"""
import datetime
import logging
import os
import threading

import app_config


class EapLogger(object):
    """
    Mysql日志管理的单例类,主要用来记录和Eap通信的mysql的日志操作类
    1) mysql操作日志文件总数量管理
    2) mysql操作日志记录
    3) 线程安全的单例模式
    """
    __instance = None
    __initFlag = False
    __lock = threading.Lock()
    debug = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            with cls.__lock:
                cls.__instance = super(EapLogger, cls).__new__(cls)
        return cls.__instance

    def __init__(self):
        if not self.__initFlag:
            print("EapLogger.__init__() 进行初始化")
            self.__initFlag = True
            self.debug = self.log_init().debug

    def log_init(self):
        """
        初始化日志模块,主要是创建日志句柄以及日志记录格式
        @return: 返回定制化的logger对象
        """
        nowTime = self.log_check()
        logger = logging.getLogger(__name__)
        logger.setLevel(level=logging.DEBUG)
        handler_ = logging.FileHandler(os.path.join(app_config.eapDebugDir, nowTime) +
                                       "_{}_debug.txt".format(app_config.projectName), encoding="UTF-8")
        handler_.setLevel(logging.DEBUG)
        formatter_ = logging.Formatter("%(asctime)s - %(message)s")
        handler_.setFormatter(formatter_)
        logger.addHandler(handler_)
        return logger

    @staticmethod
    def log_check():
        """
        日志检测,主要是日志文件数管理,删除过期日志
        @return: 返回当前日志文件使用日期
        """
        nowTime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d")
        try:
            for root, _, filenames in os.walk(app_config.eapDebugDir):
                for filename in filenames:
                    day = filename[8:10]
                    month = filename[5:7]
                    now_day = nowTime[8:10]
                    now_month = nowTime[5:7]
                    # 如果天数对应得上,但是月数不同,就删除上个月同一天的日志信息
                    if now_day == day and now_month != month:
                        os.remove(os.path.join(app_config.eapDebugDir, filename))
        except Exception as e:
            errorInfo = "in log_check() error : {}".format(str(e))
            print(errorInfo)
        return nowTime

    def print_and_debug(self, loggerInfo):
        """
        同时打印和记录到日志文件中
        @param loggerInfo: 要打印和记录的日志文件信息
        @return:
        """
        print(loggerInfo)
        self.debug(loggerInfo)
